{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!--NAVIGATION-->\n",
    "< [使用Pandas进行数据处理](03.00-Introduction-to-Pandas.ipynb) | [目录](Index.ipynb) | [数据索引和选择](03.02-Data-Indexing-and-Selection.ipynb) >\n",
    "\n",
    "<a href=\"https://colab.research.google.com/github/wangyingsm/Python-Data-Science-Handbook/blob/master/notebooks/03.01-Introducing-Pandas-Objects.ipynb\"><img align=\"left\" src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open in Colab\" title=\"Open and Execute in Google Colaboratory\"></a>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introducing Pandas Objects\n",
    "\n",
    "# Pandas对象简介"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> At the very basic level, Pandas objects can be thought of as enhanced versions of NumPy structured arrays in which the rows and columns are identified with labels rather than simple integer indices.\n",
    "As we will see during the course of this chapter, Pandas provides a host of useful tools, methods, and functionality on top of the basic data structures, but nearly everything that follows will require an understanding of what these structures are.\n",
    "Thus, before we go any further, let's introduce these three fundamental Pandas data structures: the ``Series``, ``DataFrame``, and ``Index``.\n",
    "\n",
    "在最基本的层面上，Pandas的对象可以被认为是NumPy结构化数组的一个升级版本，它的行和列都可以使用标签指代，而不仅仅像NumPy那样只能使用整数的序号。随着本章的推进，你会学习到很多Pandas提供的工具、方法和功能，但是要学习它们都需要首先理解它的数据结构。因此，在这之前，让我们先来详细介绍三个Pandas数据结构的最基本概念：`Series`、`DataFrame`和`Index`。\n",
    "\n",
    "> We will start our code sessions with the standard NumPy and Pandas imports:\n",
    "\n",
    "在写其他代码前，我们先将NumPy和Pandas按照标准方式载入："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Pandas Series Object\n",
    "\n",
    "## Pandas的Series对象\n",
    "\n",
    "> A Pandas ``Series`` is a one-dimensional array of indexed data.\n",
    "It can be created from a list or array as follows:\n",
    "\n",
    "Pandas的`Series`是一个一维的带索引序号的数组。可以通过列表或数组进行创建："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    0.25\n",
       "1    0.50\n",
       "2    0.75\n",
       "3    1.00\n",
       "dtype: float64"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = pd.Series([0.25, 0.5, 0.75, 1.0])\n",
    "data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> As we see in the output, the ``Series`` wraps both a sequence of values and a sequence of indices, which we can access with the ``values`` and ``index`` attributes.\n",
    "The ``values`` are simply a familiar NumPy array:\n",
    "\n",
    "我们从结果看到，`Series`封装了一个值的序列（由列表指定）和一个索引序号的序列，我们可以分别通过`values`和`index`属性访问它们。`values`属性就是你已经很熟悉的NumPy数组："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.25, 0.5 , 0.75, 1.  ])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.values"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> The ``index`` is an array-like object of type ``pd.Index``, which we'll discuss in more detail momentarily.\n",
    "\n",
    "`Index`是一个类似数组的对象，类型是`pd.Index`，我们很快会详细介绍它。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "RangeIndex(start=0, stop=4, step=1)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.index"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Like with a NumPy array, data can be accessed by the associated index via the familiar Python square-bracket notation:\n",
    "\n",
    "和NumPy一致，你可以通过Python的中括号加上相应的序号语法来访问数据值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.5"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1    0.50\n",
       "2    0.75\n",
       "dtype: float64"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data[1:3]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> As we will see, though, the Pandas ``Series`` is much more general and flexible than the one-dimensional NumPy array that it emulates.\n",
    "\n",
    "你将会看到，Pandas的`Series`会比它封装的一维NumPy数组通用和灵活很多。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ``Series`` as generalized NumPy array\n",
    "\n",
    "### `Series`作为通用的NumPy数组"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> From what we've seen so far, it may look like the ``Series`` object is basically interchangeable with a one-dimensional NumPy array.\n",
    "The essential difference is the presence of the index: while the Numpy Array has an *implicitly defined* integer index used to access the values, the Pandas ``Series`` has an *explicitly defined* index associated with the values.\n",
    "\n",
    "目前为止，我们看到的`Series`对象和一维NumPy数组似乎是可以互换的概念。两者最基本的区别是索引序号的存在机制：NumPy数组的整数索引*隐式提供*的，而Pandas的`Series`的索引是*显式定义*的。\n",
    "\n",
    "> This explicit index definition gives the ``Series`` object additional capabilities. For example, the index need not be an integer, but can consist of values of any desired type.\n",
    "For example, if we wish, we can use strings as an index:\n",
    "\n",
    "显式定义的索引提供了`Series`对象额外的能力。例如，索引值不需要一定是个整数，可以用任何需要的数据类型来定义索引。比方说，下面我们用字符串来作为索引："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "a    0.25\n",
       "b    0.50\n",
       "c    0.75\n",
       "d    1.00\n",
       "dtype: float64"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = pd.Series([0.25, 0.5, 0.75, 1.0],\n",
    "                 index=['a', 'b', 'c', 'd'])\n",
    "data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> And the item access works as expected:\n",
    "\n",
    "然后元素可以通过相应的索引值来访问："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.5"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data['b']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> We can even use non-contiguous or non-sequential indices:\n",
    "\n",
    "我们亦可以使用非连续的或非序列的索引值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2    0.25\n",
       "5    0.50\n",
       "3    0.75\n",
       "7    1.00\n",
       "dtype: float64"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = pd.Series([0.25, 0.5, 0.75, 1.0],\n",
    "                 index=[2, 5, 3, 7])\n",
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.5"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data[5]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Series as specialized dictionary\n",
    "\n",
    "### Series作为特殊的字典\n",
    "\n",
    "> In this way, you can think of a Pandas ``Series`` a bit like a specialization of a Python dictionary.\n",
    "A dictionary is a structure that maps arbitrary keys to a set of arbitrary values, and a ``Series`` is a structure which maps typed keys to a set of typed values.\n",
    "This typing is important: just as the type-specific compiled code behind a NumPy array makes it more efficient than a Python list for certain operations, the type information of a Pandas ``Series`` makes it much more efficient than Python dictionaries for certain operations.\n",
    "\n",
    "在这个层面上，你可以将Pandas的`Series`当成Python字典的一种特殊情形。Python中的字典可以将任意的关键字key和任意的值value对应起来，`Series`是一种能将特定类型的关键字key和特定类型的值value对应起来的字典。这种静态类型是很重要的：正如NumPy数组的静态类型能提供编译好的代码提升对Python列表或集合的操作性能一样，Pandas的`Series`能提供编译好的代码提升对Python字典的操作性能。\n",
    "\n",
    "> The ``Series``-as-dictionary analogy can be made even more clear by constructing a ``Series`` object directly from a Python dictionary:\n",
    "\n",
    "用一个Python字典创建一个`Series`，更加方便理解`Series`作为一个字典的机制："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "California    38332521\n",
       "Texas         26448193\n",
       "New York      19651127\n",
       "Florida       19552860\n",
       "Illinois      12882135\n",
       "dtype: int64"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "population_dict = {'California': 38332521,\n",
    "                   'Texas': 26448193,\n",
    "                   'New York': 19651127,\n",
    "                   'Florida': 19552860,\n",
    "                   'Illinois': 12882135}\n",
    "population = pd.Series(population_dict)\n",
    "population"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> By default, a ``Series`` will be created where the index is drawn from the sorted keys.\n",
    "From here, typical dictionary-style item access can be performed:\n",
    "\n",
    "默认情况下，`Series`会以排序关键字的方式创建一个字典。然后就可以使用Python标准的字典语法获取值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "38332521"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "population['California']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Unlike a dictionary, though, the ``Series`` also supports array-style operations such as slicing:\n",
    "\n",
    "下面这个操作是字典所不具有的，`Series`还支持按照数组方式的操作来对字典进行切片："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "California    38332521\n",
       "Texas         26448193\n",
       "New York      19651127\n",
       "Florida       19552860\n",
       "Illinois      12882135\n",
       "dtype: int64"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "population['California':'Illinois']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> We'll discuss some of the quirks of Pandas indexing and slicing in [Data Indexing and Selection](03.02-Data-Indexing-and-Selection.ipynb).\n",
    "\n",
    "我们会在[数据索引和选择](03.02-Data-Indexing-and-Selection.ipynb)中更详细介绍Pandas索引和切片操作。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Constructing Series objects\n",
    "\n",
    "### 构建Series对象\n",
    "\n",
    "> We've already seen a few ways of constructing a Pandas ``Series`` from scratch; all of them are some version of the following:\n",
    "\n",
    "我们已经看到几种构建Pandas的`Series`对象的方法；其语法基础都是下面的构造方法：\n",
    "\n",
    "```python\n",
    ">>> pd.Series(data, index=index)\n",
    "```\n",
    "\n",
    "> where ``index`` is an optional argument, and ``data`` can be one of many entities.\n",
    "\n",
    "其中的`index`是一个可选的参数，而`data`可以使很多种的数据集合。\n",
    "\n",
    "> For example, ``data`` can be a list or NumPy array, in which case ``index`` defaults to an integer sequence:\n",
    "\n",
    "例如，`data`可以是一个列表或NumPy数组，在这种情况下`index`默认是一个整数序列："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    2\n",
       "1    4\n",
       "2    6\n",
       "dtype: int64"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Series([2, 4, 6])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> ``data`` can be a scalar, which is repeated to fill the specified index:\n",
    "\n",
    "`data`可以是一个标量，这种情况下标量的值会填充到整个序列的index中："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "100    5\n",
       "200    5\n",
       "300    5\n",
       "dtype: int64"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Series(5, index=[100, 200, 300])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> ``data`` can be a dictionary, in which ``index`` defaults to the sorted dictionary keys:\n",
    "\n",
    "`data`可以是一个字典，这种情况下`index`默认是一个排序的关键字key序列："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2    a\n",
       "1    b\n",
       "3    c\n",
       "dtype: object"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Series({2:'a', 1:'b', 3:'c'})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> In each case, the index can be explicitly set if a different result is preferred:\n",
    "\n",
    "每种情况下，index都可以作为额外的明确指定索引的方式，结果也会依据index参数而发生变化："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3    c\n",
       "2    a\n",
       "dtype: object"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Series({2:'a', 1:'b', 3:'c'}, index=[3, 2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Notice that in this case, the ``Series`` is populated only with the explicitly identified keys.\n",
    "\n",
    "上例表明，结果中包含的数据仅是index明确指定部分。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Pandas DataFrame Object\n",
    "\n",
    "## Pandas的DaraFrame对象\n",
    "\n",
    "> The next fundamental structure in Pandas is the ``DataFrame``.\n",
    "Like the ``Series`` object discussed in the previous section, the ``DataFrame`` can be thought of either as a generalization of a NumPy array, or as a specialization of a Python dictionary.\n",
    "We'll now take a look at each of these perspectives.\n",
    "\n",
    "Pandas的另一个基础数据结构是`DataFrame`。就像刚才介绍的`Series`一样，`DataFrame`既可以被当成是一种更通用的NumPy数组，也可以被当成是一种特殊的Python字典。下面来分别看看。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### DataFrame as a generalized NumPy array\n",
    "\n",
    "### DataFrame作为一种通用的NumPy数组\n",
    "\n",
    "> If a ``Series`` is an analog of a one-dimensional array with flexible indices, a ``DataFrame`` is an analog of a two-dimensional array with both flexible row indices and flexible column names.\n",
    "Just as you might think of a two-dimensional array as an ordered sequence of aligned one-dimensional columns, you can think of a ``DataFrame`` as a sequence of aligned ``Series`` objects.\n",
    "Here, by \"aligned\" we mean that they share the same index.\n",
    "\n",
    "如果说`Series`是带有灵活索引的通用一维数组的话，那么`DataFrame`就是带有灵活的行索引和列索引的通用二维数组。你也可以将`DataFrame`想象成一系列的`Series`对象堆叠在一起，所谓的堆叠实际上指的是这些`Series`拥有相同的索引值序列。\n",
    "\n",
    "> To demonstrate this, let's first construct a new ``Series`` listing the area of each of the five states discussed in the previous section:\n",
    "\n",
    "下面我们构建一个新的`Series`存储着美国5个州面积（和上面的州人口例子一致）来说明这一点："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "California    423967\n",
       "Texas         695662\n",
       "New York      141297\n",
       "Florida       170312\n",
       "Illinois      149995\n",
       "dtype: int64"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "area_dict = {'California': 423967, 'Texas': 695662, 'New York': 141297,\n",
    "             'Florida': 170312, 'Illinois': 149995}\n",
    "area = pd.Series(area_dict)\n",
    "area"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Now that we have this along with the ``population`` Series from before, we can use a dictionary to construct a single two-dimensional object containing this information:\n",
    "\n",
    "现在我们就有了两个`Series`，一个人口和一个面积，我们可以再使用一个字典来创建一个二维的对象来存储两个序列的数据："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>population</th>\n",
       "      <th>area</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>California</th>\n",
       "      <td>38332521</td>\n",
       "      <td>423967</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Texas</th>\n",
       "      <td>26448193</td>\n",
       "      <td>695662</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>New York</th>\n",
       "      <td>19651127</td>\n",
       "      <td>141297</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Florida</th>\n",
       "      <td>19552860</td>\n",
       "      <td>170312</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Illinois</th>\n",
       "      <td>12882135</td>\n",
       "      <td>149995</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            population    area\n",
       "California    38332521  423967\n",
       "Texas         26448193  695662\n",
       "New York      19651127  141297\n",
       "Florida       19552860  170312\n",
       "Illinois      12882135  149995"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "states = pd.DataFrame({'population': population,\n",
    "                       'area': area})\n",
    "states"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Like the ``Series`` object, the ``DataFrame`` has an ``index`` attribute that gives access to the index labels:\n",
    "\n",
    "`DataFrame`对象也像`Series`一样有着`index`属性，包括所有的数据的索引标签："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['California', 'Texas', 'New York', 'Florida', 'Illinois'], dtype='object')"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "states.index"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Additionally, the ``DataFrame`` has a ``columns`` attribute, which is an ``Index`` object holding the column labels:\n",
    "\n",
    "因为上面的`DataFrame`是二维的，因此它额外含有一个`columns`属性，同样也是一个`Index`对象，存储这所有列的标签："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['population', 'area'], dtype='object')"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "states.columns"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Thus the ``DataFrame`` can be thought of as a generalization of a two-dimensional NumPy array, where both the rows and columns have a generalized index for accessing the data.\n",
    "\n",
    "因此`DataFrame`也可以被看成是二维NumPy数组的通用形式，它的行和列都带有通用的索引序列用来访问数据。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### DataFrame as specialized dictionary\n",
    "\n",
    "### DataFrame作为特殊的字典\n",
    "\n",
    "> Similarly, we can also think of a ``DataFrame`` as a specialization of a dictionary.\n",
    "Where a dictionary maps a key to a value, a ``DataFrame`` maps a column name to a ``Series`` of column data.\n",
    "For example, asking for the ``'area'`` attribute returns the ``Series`` object containing the areas we saw earlier:\n",
    "\n",
    "类似`Series`，我们也可以将`DataFrame`看成是一种特殊的字典。普通的字典将一个关键字key映射成一个值value，而`DataFrame`将一个列标签映射成一个`Series`对象，里面含有整列的数据。例如，访问`area`属性会返回一个`Series`对象包含前面我们放入的面积数据："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "California    423967\n",
       "Texas         695662\n",
       "New York      141297\n",
       "Florida       170312\n",
       "Illinois      149995\n",
       "Name: area, dtype: int64"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "states['area']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Notice the potential point of confusion here: in a two-dimesnional NumPy array, ``data[0]`` will return the first *row*. For a ``DataFrame``, ``data['col0']`` will return the first *column*.\n",
    "Because of this, it is probably better to think about ``DataFrame``s as generalized dictionaries rather than generalized arrays, though both ways of looking at the situation can be useful.\n",
    "We'll explore more flexible means of indexing ``DataFrame``s in [Data Indexing and Selection](03.02-Data-Indexing-and-Selection.ipynb).\n",
    "\n",
    "这里要注意一下容易混淆的地方：NumPy的二维数组中，`data[0]`会返回第一行数据，而在`DataFrame`中，`data['col0']`会返回第一列数据。正因为此，最好还是将`DataFrame`当成是一个特殊的字典而不是通用的二维数组。我们会在[数据的索引和选择](03.02-Data-Indexing-and-Selection.ipynb)一节中详细讨论更多更灵活的索引操作。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Constructing DataFrame objects\n",
    "\n",
    "### 构建DataFrame对象\n",
    "\n",
    "> A Pandas ``DataFrame`` can be constructed in a variety of ways.\n",
    "Here we'll give several examples.\n",
    "\n",
    "Pandas中的`DataFrame`可以有多种方法进行构建。下面我们介绍几个方式。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### From a single Series object\n",
    "\n",
    "#### 从单个Series对象构建\n",
    "\n",
    "> A ``DataFrame`` is a collection of ``Series`` objects, and a single-column ``DataFrame`` can be constructed from a single ``Series``:\n",
    "\n",
    "`DataFrame`是`Series`对象的集合，因此单列的`DataFrame`可以从单个的`Series`对象创建："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>population</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>California</th>\n",
       "      <td>38332521</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Texas</th>\n",
       "      <td>26448193</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>New York</th>\n",
       "      <td>19651127</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Florida</th>\n",
       "      <td>19552860</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Illinois</th>\n",
       "      <td>12882135</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            population\n",
       "California    38332521\n",
       "Texas         26448193\n",
       "New York      19651127\n",
       "Florida       19552860\n",
       "Illinois      12882135"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.DataFrame(population, columns=['population'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### From a list of dicts\n",
    "\n",
    "#### 从字典的列表构建\n",
    "\n",
    "> Any list of dictionaries can be made into a ``DataFrame``.\n",
    "We'll use a simple list comprehension to create some data:\n",
    "\n",
    "任何字典的列表都可以用来创建`DataFrame`，我们使用一个简单的列表解析表达式来创建一个DataFrame："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a</th>\n",
       "      <th>b</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   a  b\n",
       "0  0  0\n",
       "1  1  2\n",
       "2  2  4"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = [{'a': i, 'b': 2 * i}\n",
    "        for i in range(3)]\n",
    "pd.DataFrame(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Even if some keys in the dictionary are missing, Pandas will fill them in with ``NaN`` (i.e., \"not a number\") values:\n",
    "\n",
    "甚至在某些关键字对应的值在字典中不存在的情况下，Pandas会自动将它们填充为`NaN`（非数字）值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a</th>\n",
       "      <th>b</th>\n",
       "      <th>c</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1.0</td>\n",
       "      <td>2</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>NaN</td>\n",
       "      <td>3</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     a  b    c\n",
       "0  1.0  2  NaN\n",
       "1  NaN  3  4.0"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.DataFrame([{'a': 1, 'b': 2}, {'b': 3, 'c': 4}])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### From a dictionary of Series objects\n",
    "\n",
    "#### 从Series对象的字典构建\n",
    "\n",
    "> As we saw before, a ``DataFrame`` can be constructed from a dictionary of ``Series`` objects as well:\n",
    "\n",
    "我们之前看到`DataFrame`可以从一个`Series`对象构成的字典中创建："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>population</th>\n",
       "      <th>area</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>California</th>\n",
       "      <td>38332521</td>\n",
       "      <td>423967</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Texas</th>\n",
       "      <td>26448193</td>\n",
       "      <td>695662</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>New York</th>\n",
       "      <td>19651127</td>\n",
       "      <td>141297</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Florida</th>\n",
       "      <td>19552860</td>\n",
       "      <td>170312</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Illinois</th>\n",
       "      <td>12882135</td>\n",
       "      <td>149995</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            population    area\n",
       "California    38332521  423967\n",
       "Texas         26448193  695662\n",
       "New York      19651127  141297\n",
       "Florida       19552860  170312\n",
       "Illinois      12882135  149995"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.DataFrame({'population': population,\n",
    "              'area': area})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### From a two-dimensional NumPy array\n",
    "\n",
    "#### 从一个二维NumPy数组构建\n",
    "\n",
    "> Given a two-dimensional array of data, we can create a ``DataFrame`` with any specified column and index names.\n",
    "If omitted, an integer index will be used for each:\n",
    "\n",
    "在给定一个二维NumPy数组的情况下，我们指定其相应的列和行的索引序列来构建一个`DataFrame`。如果行或列的index没有指定，默认会使用一个整数索引序列来指定："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>foo</th>\n",
       "      <th>bar</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>a</th>\n",
       "      <td>0.435638</td>\n",
       "      <td>0.153130</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>b</th>\n",
       "      <td>0.070155</td>\n",
       "      <td>0.671968</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>c</th>\n",
       "      <td>0.974456</td>\n",
       "      <td>0.358945</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        foo       bar\n",
       "a  0.435638  0.153130\n",
       "b  0.070155  0.671968\n",
       "c  0.974456  0.358945"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.DataFrame(np.random.rand(3, 2),\n",
    "             columns=['foo', 'bar'],\n",
    "             index=['a', 'b', 'c'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### From a NumPy structured array\n",
    "\n",
    "#### 从NumPy结构化数组构建\n",
    "\n",
    "> We covered structured arrays in [Structured Data: NumPy's Structured Arrays](02.09-Structured-Data-NumPy.ipynb).\n",
    "A Pandas ``DataFrame`` operates much like a structured array, and can be created directly from one:\n",
    "\n",
    "上一章最后一节我们介绍了结构化数组（参见[结构化数据：NumPy结构化数组](02.09-Structured-Data-NumPy.ipynb)）。Pandas的`DataFrame`对象与结构化数组非常接近，因此可以直接从后者构建："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([(0, 0.), (0, 0.), (0, 0.)], dtype=[('A', '<i8'), ('B', '<f8')])"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A = np.zeros(3, dtype=[('A', 'i8'), ('B', 'f8')])\n",
    "A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>A</th>\n",
       "      <th>B</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   A    B\n",
       "0  0  0.0\n",
       "1  0  0.0\n",
       "2  0  0.0"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.DataFrame(A)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Pandas Index Object\n",
    "\n",
    "## Pandas的Index对象\n",
    "\n",
    "> We have seen here that both the ``Series`` and ``DataFrame`` objects contain an explicit *index* that lets you reference and modify data.\n",
    "This ``Index`` object is an interesting structure in itself, and it can be thought of either as an *immutable array* or as an *ordered set* (technically a multi-set, as ``Index`` objects may contain repeated values).\n",
    "Those views have some interesting consequences in the operations available on ``Index`` objects.\n",
    "As a simple example, let's construct an ``Index`` from a list of integers:\n",
    "\n",
    "前面内容介绍的`Series`和`DataFrame`对象都包含着一个显式定义的*索引index*对象，它的作用就是让你快速访问和修改数据。`Index`对象是一个很有趣的数据结构，它可以被当成*不可变的数组*或者*排序的集合*（严格来说是多数据集合，因为`Index`允许包含重复的值）。这两种看法在对`Index`对象进行操作时会产生一些很有趣的结果。先以一个简单的例子来说明，我们从整数列表构建一个`Index`对象："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Int64Index([2, 3, 5, 7, 11], dtype='int64')"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ind = pd.Index([2, 3, 5, 7, 11])\n",
    "ind"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Index as immutable array\n",
    "\n",
    "### Index作为不可变数组\n",
    "\n",
    "> The ``Index`` in many ways operates like an array.\n",
    "For example, we can use standard Python indexing notation to retrieve values or slices:\n",
    "\n",
    "`Index`很多的操作都像一个数组。例如，我们可以使用标准的Python索引语法来获得值和切片："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ind[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Int64Index([2, 5, 11], dtype='int64')"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ind[::2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> ``Index`` objects also have many of the attributes familiar from NumPy arrays:\n",
    "\n",
    "`Index`对象也有很多你熟悉的NumPy数组属性："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 (5,) 1 int64\n"
     ]
    }
   ],
   "source": [
    "print(ind.size, ind.shape, ind.ndim, ind.dtype)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> One difference between ``Index`` objects and NumPy arrays is that indices are immutable–that is, they cannot be modified via the normal means:\n",
    "\n",
    "NumPy数组和`Index`对象的最大区别是你无法改变`Index`的元素值，它们是不可变的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "Index does not support mutable operations",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-37-906a9fa1424c>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mind\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m~/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py\u001b[0m in \u001b[0;36m__setitem__\u001b[0;34m(self, key, value)\u001b[0m\n\u001b[1;32m   3936\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   3937\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0m__setitem__\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkey\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 3938\u001b[0;31m         \u001b[0;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Index does not support mutable operations\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   3939\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   3940\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0m__getitem__\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mTypeError\u001b[0m: Index does not support mutable operations"
     ]
    }
   ],
   "source": [
    "ind[1] = 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> This immutability makes it safer to share indices between multiple ``DataFrame``s and arrays, without the potential for side effects from inadvertent index modification.\n",
    "\n",
    "这种不变性能在多个`DataFrame`之间共享索引时提供一种安全性，避免因为疏忽造成的索引修改和其他的副作用。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Index as ordered set\n",
    "\n",
    "### Index作为排序集合\n",
    "\n",
    "> Pandas objects are designed to facilitate operations such as joins across datasets, which depend on many aspects of set arithmetic.\n",
    "The ``Index`` object follows many of the conventions used by Python's built-in ``set`` data structure, so that unions, intersections, differences, and other combinations can be computed in a familiar way:\n",
    "\n",
    "Pandas对象被设计成能够满足跨数据集进行操作，例如连接多个数据集查找或操作数据，这很大程度依赖于集合运算。`Index`对象遵循Python內建的`set`数据结构的运算法则，因此并集、交集、差集和其他的集合操作也可以按照熟悉的方式进行："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "indA = pd.Index([1, 3, 5, 7, 9])\n",
    "indB = pd.Index([2, 3, 5, 7, 11])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Int64Index([3, 5, 7], dtype='int64')"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "indA & indB  # 交集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Int64Index([1, 2, 3, 5, 7, 9, 11], dtype='int64')"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "indA | indB  # 并集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Int64Index([1, 2, 9, 11], dtype='int64')"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "indA ^ indB  # 互斥差集"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> These operations may also be accessed via object methods, for example ``indA.intersection(indB)``.\n",
    "\n",
    "这些操作也可以通过对象的方法来实现，例如`indA.intersection(indB)`。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!--NAVIGATION-->\n",
    "< [使用Pandas进行数据处理](03.00-Introduction-to-Pandas.ipynb) | [目录](Index.ipynb) | [数据索引和选择](03.02-Data-Indexing-and-Selection.ipynb) >\n",
    "\n",
    "<a href=\"https://colab.research.google.com/github/wangyingsm/Python-Data-Science-Handbook/blob/master/notebooks/03.01-Introducing-Pandas-Objects.ipynb\"><img align=\"left\" src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open in Colab\" title=\"Open and Execute in Google Colaboratory\"></a>\n"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
